<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue'

type Direction = 'prev' | 'next'

const imgIds = [30, 39, 60, 65, 160, 169, 180, 304]
const images = [...Array(8).keys()].map((i) => ({
  id: imgIds[i],
  imgUrl: `https://picsum.photos/id/${imgIds[i]}/300/200`
}))
const containerRef = ref<HTMLDivElement | null>(null)
let angle = 0
let direction: Direction = 'next'
let timer: NodeJS.Timeout
onMounted(() => {
  autoRorating()
})

onUnmounted(() => {
  clearTimeout(timer)
})

function autoRorating() {
  if (containerRef.value) {
    console.log('running?')
    containerRef.value.style.transform = `perspective(1000px) rotateY(${angle}deg)`

    timer = setTimeout(() => {
      if (direction === 'next') {
        angle += 45
      } else if (direction === 'prev') {
        angle -= 45
      }
      autoRorating()
    }, 2000)
  }
}

function handleClick(flag: Direction) {
  clearTimeout(timer)
  angle = angle + (flag === 'next' ? 45 : -45)
  direction = flag
  autoRorating()
}
</script>

<template>
  <div class="rorating-image-gallery__frame">
    <div ref="containerRef" class="container">
      <span v-for="(img, index) in images" :key="img.id" :style="{ '--i': index + 1 }">
        <img :src="img.imgUrl" />
      </span>
    </div>
    <div class="btns">
      <div class="btn prev" @click="handleClick('prev')">Prev</div>
      <div class="btn next" @click="handleClick('next')">Next</div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.rorating-image-gallery__frame {
  width: 100%;
  height: 100%;
  display: grid;
  place-items: center;

  .container {
    position: relative;
    width: 200px;
    height: 200px;
    /* -----------------打开这个盒子是为了方便理解------------------------ */
    border: 1px solid black;
    background-color: rgb(205, 129, 29);
    /* ----------------------------------------- */
    transform-style: preserve-3d;
    transform: perspective(1000px) rotateY(0deg);
    transition: all 0.5s linear;

    span {
      position: absolute;
      width: 100%;
      top: 0;
      left: 0;
      transform: rotateY(calc(var(--i) * -45deg)) translateZ(400px);
      img {
        position: absolute;
        width: 100%;
      }
    }
  }

  .btns {
    width: 80%;
    display: flex;
    justify-content: space-between;
    border: 1px solid black;

    position: relative;

    .btn {
      padding: 10px 15px;
      border-radius: 5px;
      color: #fff;
      background-color: rgb(15, 120, 63);
      cursor: pointer;

      &:hover {
        filter: brightness(1.5);
      }

      position: absolute;
      bottom: 100px;

      &.prev {
        left: 20%;
      }

      &.next {
        right: 20%;
      }
    }
  }
}
</style>
